package org.jeecg.modules.sistersophie.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.sistersophie.constans.GlobalConstans;
import org.jeecg.modules.sistersophie.entity.CourseInfo;
import org.jeecg.modules.sistersophie.facade.CourseInfoFacade;
import org.jeecg.modules.sistersophie.facade.CourseStudentFacade;
import org.jeecg.modules.sistersophie.service.ICourseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: course_info
 * @Author: jeecg-boot
 * @Date:   2021-06-04
 * @Version: V1.0
 */
@Api(tags="course_info")
@RestController
@RequestMapping("/sistersophie/courseInfo")
@Slf4j
public class CourseInfoController extends JeecgController<CourseInfo, ICourseInfoService> {
	@Autowired
	private ICourseInfoService courseInfoService;

	@Autowired
	private CourseInfoFacade courseInfoFacade;

	@Autowired
	private CourseStudentFacade courseStudentFacade;
	
	/**
	 * 分页列表查询
	 *
	 * @param courseInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "course_info-分页列表查询")
	@ApiOperation(value="course_info-分页列表查询", notes="course_info-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(CourseInfo courseInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		courseInfo.setIsDelete(0);
		QueryWrapper<CourseInfo> queryWrapper = QueryGenerator.initQueryWrapper(courseInfo, req.getParameterMap());
		Page<CourseInfo> page = new Page<CourseInfo>(pageNo, pageSize);
		if(StringUtils.isNotBlank(courseInfo.getYear())){
			queryWrapper.apply("date_format(start_time,'%Y') = {0}",courseInfo.getYear());
			//queryWrapper.apply("date_format(end_time,'%Y') = {0}",courseInfo.getYear());
		}
		if(StringUtils.isNotBlank(courseInfo.getTeacherIds())){
			queryWrapper.in("teacher_id",courseInfo.getTeacherIds().split(","));
		}
		IPage<CourseInfo> pageList = courseInfoService.page(page, queryWrapper);
		if(pageList != null && pageList.getRecords() != null && pageList.getRecords().size() > 0){
			for(CourseInfo info : pageList.getRecords()){
				info.setTearcherName(info.getTeacherFirstName() + " " + info.getTeacherLastName());
				if(info.getPrice() != null){
					info.setPriceFormat(info.getCurrency() + NumberUtil.decimalFormat(GlobalConstans.DECIMARPATTERN,info.getPrice()));
				}
				//获取当前课程的学生数量
				int num = courseStudentFacade.selectCourseStudentCount(info.getId());
				String enrollment = num + "/" + info.getMaxStudent();
				info.setEnrollment(enrollment);
			}
		}
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param courseInfo
	 * @return
	 */
	@AutoLog(value = "course_info-添加")
	@ApiOperation(value="course_info-添加", notes="course_info-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody CourseInfo courseInfo) {
		courseInfoFacade.addCourseInfo(courseInfo);
		return Result.OK("Saved successfully！");
	}
	
	/**
	 *  编辑
	 *
	 * @param courseInfo
	 * @return
	 */
	@AutoLog(value = "course_info-编辑")
	@ApiOperation(value="course_info-编辑", notes="course_info-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody CourseInfo courseInfo) {

		int num = courseStudentFacade.selectCourseStudentCount(courseInfo.getId());

		if(courseInfo.getCourseType() != null && courseInfo.getCourseType().intValue() == 1){
			courseInfo.setMaxStudent(courseInfo.getCourseSubType());
		}
		if(courseInfo.getMaxStudent() < num){
			throw new RuntimeException("The maximum number of students is too small");
		}

		List<CourseInfo> courseInfos =  courseInfoService.selectByNameNotIn(courseInfo.getName(),courseInfo.getId());
		if(courseInfos != null && courseInfos.size() > 0){
			throw new RuntimeException(courseInfo.getName()  + " already exists, please re-enter");
		}

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		courseInfo.setUpdateName(sysUser.getUsername());
		courseInfo.setUpdateTime(new Date());
		courseInfo.setIsDelete(0);
		courseInfoService.updateById(courseInfo);
		return Result.OK("Saved successfully!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "course_info-通过id删除")
	@ApiOperation(value="course_info-通过id删除", notes="course_info-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		/*courseInfoService.removeById(id);*/
		courseInfoFacade.deleteCourse(id);
		return Result.OK("Cancel successfully！");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "course_info-批量删除")
	@ApiOperation(value="course_info-批量删除", notes="course_info-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.courseInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "course_info-通过id查询")
	@ApiOperation(value="course_info-通过id查询", notes="course_info-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CourseInfo courseInfo = courseInfoService.getById(id);
		if(courseInfo==null) {
			return Result.error("未找到对应数据");
		}
		courseInfo.setTearcherName(courseInfo.getTeacherFirstName() +" " + courseInfo.getTeacherLastName());
		return Result.OK(courseInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param courseInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CourseInfo courseInfo) {
        return super.exportXls(request, courseInfo, CourseInfo.class, "course_info");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CourseInfo.class);
    }

}
